<template>
  <div class="id-card-container">
    <!-- 拍照界面 -->
    <div v-if="!photoData" class="camera-box">
      <video ref="videoRef" class="camera-view" autoplay></video>
      <div class="overlay">
        <div class="id-card-frame"></div>
      </div>

      <div class="action-buttons">
        <van-button
            type="primary"
            round
            icon="photograph"
            @click="takePhoto"
        >
          拍摄
        </van-button>
        <van-button
            round
            icon="replay"
            @click="switchCamera"
        >
          切换镜头
        </van-button>
      </div>
    </div>

    <!-- 拍摄结果 -->
    <div v-else class="preview-box">
      <img :src="photoData" class="preview-image" />
      <div class="preview-actions">
        <van-button type="danger" @click="retake">重拍</van-button>
        <van-button type="primary" @click="confirmPhoto">确认使用</van-button>
      </div>
    </div>

    <!-- 类型选择 -->
    <div class="type-selector">
      <van-radio-group v-model="cardType">
        <van-radio name="front">身份证正面</van-radio>
        <van-radio name="back">身份证反面</van-radio>
      </van-radio-group>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { showToast } from 'vant'

const videoRef = ref(null)
const photoData = ref('')
const cardType = ref('front')
let mediaStream = null

// 初始化摄像头
const initCamera = async (facingMode = 'environment') => {
  try {
    const constraints = {
      video: {
        facingMode: facingMode,
        width: { ideal: 1280 },
        height: { ideal: 720 }
      }
    }

    mediaStream = await navigator.mediaDevices.getUserMedia(constraints)
    if (videoRef.value) {
      videoRef.value.srcObject = mediaStream
    }
  } catch (error) {
    showToast('摄像头访问失败，请检查权限')
    //console.error('摄像头错误:', error)
  }
}

// 拍照功能
const takePhoto = () => {
  const canvas = document.createElement('canvas')
  const video = videoRef.value
  const ctx = canvas.getContext('2d')

  // 设置画布尺寸（根据身份证比例调整）
  canvas.width = 640
  canvas.height = 400

  // 绘制图像并自动裁剪
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

  // 压缩图片质量
  photoData.value = canvas.toDataURL('image/jpeg', 0.7)
}

// 切换摄像头
const switchCamera = () => {
  stopCamera()
  const newMode = mediaStream?.getVideoTracks()[0]?.getSettings().facingMode === 'user'
      ? 'environment'
      : 'user'
  initCamera(newMode)
}

// 重新拍摄
const retake = () => {
  photoData.value = ''
  initCamera()
}

// 确认使用照片
const confirmPhoto = () => {
  // 这里可以添加上传逻辑
  //console.log('确认使用的照片:', photoData.value)
  showToast('上传成功')
}

// 停止摄像头
const stopCamera = () => {
  if (mediaStream) {
    mediaStream.getTracks().forEach(track => track.stop())
  }
}

onMounted(() => {
  initCamera()
})

onUnmounted(() => {
  stopCamera()
})
</script>

<style scoped>
.id-card-container {
  height: 100vh;
  background: #000;
}

.camera-box {
  position: relative;
  height: 70vh;
}

.camera-view {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.id-card-frame {
  width: 300px;
  height: 200px;
  border: 2px solid #00ff00;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 255, 0, 0.3);
}

.action-buttons {
  position: absolute;
  bottom: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.preview-box {
  height: 70vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-image {
  width: 300px;
  height: 200px;
  border-radius: 8px;
  margin-top: 20px;
  border: 2px solid #fff;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  gap: 20px;
}

.type-selector {
  padding: 20px;
  background: #fff;
}

.van-radio {
  margin: 10px 0;
}
</style>